﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using Newtonsoft.Json.Linq;
using System.Data;
using System.Text.RegularExpressions;
using System.Net;
using System.Text;
using System.IO;
using SZHL.Data;

namespace SZHL.UI.AppCode
{
    public class CommonHelp
    {
        /// <summary>
        /// 绑定类
        /// </summary>
        public class BindData
        {
            /// <summary>
            /// 绑定部门
            /// </summary>
            /// <param name="ddl"></param>
            public void BindBranch(DropDownList ddl, string strISALL = "N")
            {
                if (strISALL == "N")
                {
                    ddl.DataSource = new JH_Auth_BranchB().GetEntities(d => d.DeptCode != 0 && d.DeptCode != 1);

                }
                else
                {
                    ddl.DataSource = new JH_Auth_BranchB().GetEntities(d => d.DeptCode != 0);
                }
                ddl.DataTextField = "DeptName";
                ddl.DataValueField = "DeptCode";
                ddl.DataBind();
            }


            /// <summary>
            /// 绑定页码
            /// </summary>
            /// <param name="ddl"></param>
            /// <param name="Page"></param>
            public void BindPage(DropDownList ddl, int Page)
            {
                ddl.Items.Clear();
                if (Page == 0)
                {
                    ddl.Items.Add(new ListItem() { Text = "1", Value = "1" });
                }
                else
                {
                    for (int i = 1; i <= Page; i++)
                    {
                        ddl.Items.Add(new ListItem() { Text = i.ToString(), Value = i.ToString() });
                    }
                }

            }

            public void BindAllPeopleSmart(DropDownList ddl)
            {
                ListItem liFirst = new ListItem("请选择", "");
                ddl.Items.Add(liFirst);
                List<JH_Auth_Branch> ListBranch = new JH_Auth_BranchB().GetEntities(d => d.DeptName != "组织机构").ToList();
                foreach (var item in ListBranch)
                {
                    ListItem liBranch = new ListItem(item.DeptName, "optgroup");
                    ddl.Items.Add(liBranch);
                    string strListUsers = new JH_Auth_UserB().GetAllUserListByBranch(item.DeptCode).Trim();
                    if (strListUsers.Length > 0)
                    {
                        foreach (var itemuser in strListUsers.Split(','))
                        {
                            if (itemuser!="admin")
                            {
                                ListItem liUser = new ListItem(new JH_Auth_UserB().GetUserRealName(itemuser), itemuser);
                                ddl.Items.Add(liUser);
                            }

                        }
                    }
                }
            }




            #region 业务绑定

            /// <summary>
            /// 绑定字典数据
            /// </summary>
            /// <param name="ddl"></param>
            /// <param name="strClass"></param>
            public void BindZiDian(DropDownList ddl, string strClass)
            {

                ddl.DataSource = new JH_Auth_ZiDianB().GetEntities(d => d.Class.ToString() == strClass);
                ddl.DataTextField = "TypeName";
                ddl.DataValueField = "TypeName";
                ddl.DataBind();
            }


            /// <summary>
            /// 绑定审核人（出差请假，经费报销）
            /// </summary>
            /// <param name="ddl"></param>
            /// <param name="strClass"></param>
            public void BindSHR(DropDownList ddl, int strRoleCode = 4)
            {

                ddl.DataSource = new JH_Auth_UserRoleB().GetUserDTByRoleCode(strRoleCode);
                ddl.DataTextField = "userrealname";
                ddl.DataValueField = "username";
                ddl.DataBind();
            }


            #endregion
        }


        public class SessionHelper
        {
            /// <summary>
            /// 根据session名获取session对象
            /// </summary>
            /// <param name="name"></param>
            /// <returns></returns>
            public static object GetSession(string name)
            {
                return HttpContext.Current.Session[name];
            }
            /// <summary>
            /// 设置session,sharejs.com
            /// </summary>
            /// <param name="name">session 名</param>
            /// <param name="val">session 值</param>
            public static void SetSession(string name, object val)
            {
                HttpContext.Current.Session.Remove(name);
                HttpContext.Current.Session.Add(name, val);
            }
        }


        /// <summary>
        /// 从html中提取纯文本
        /// </summary>
        /// <param name="strHtml"></param>
        /// <returns></returns>
        public string StripHT(string strHtml)  //从html中提取纯文本
        {
            Regex regex = new Regex("<.+?>", RegexOptions.IgnoreCase);
            string strOutput = regex.Replace(strHtml, "");//替换掉"<"和">"之间的内容
            strOutput = strOutput.Replace("<", "");
            strOutput = strOutput.Replace(">", "");
            strOutput = strOutput.Replace("&nbsp;", "");
            return strOutput;
        }

        /// <summary>  
        /// 创建POST方式的HTTP请求  
        /// </summary>  
        public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, int timeout, string userAgent, CookieCollection cookies)
        {
            HttpWebRequest request = null;
            //如果是发送HTTPS请求  
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(url) as HttpWebRequest;
                //request.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
           
            //设置代理UserAgent和超时
            //request.UserAgent = userAgent;
            //request.Timeout = timeout; 

            if (cookies != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookies);
            }
            //发送POST数据  
            if (!(parameters == null || parameters.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, parameters[key]);
                        i++;
                    }
                }
                byte[] data = Encoding.UTF8.GetBytes(buffer.ToString());
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            string[] values = request.Headers.GetValues("Content-Type");
            return request.GetResponse() as HttpWebResponse;
        }

        /// <summary>
        /// 获取请求的数据
        /// </summary>
        public static string GetResponseString(HttpWebResponse webresponse)
        {
            using (Stream s = webresponse.GetResponseStream())
            {
                StreamReader reader = new StreamReader(s, Encoding.UTF8);
                return reader.ReadToEnd();

            }
        }

        public static void SendSMS(string telephone, string content)
        {
            try
            {
                SmsService.LinkWS api = new SmsService.LinkWS();

                string[] tels = telephone.Split(',');

                foreach (string tel in tels)
                {
                    string re = api.Send2("SY0189", "77672528", tel, content + "【企捷】", "", "");
                }

                //if (telephone.Contains(","))
                //{
                //    string re = api.BatchSend2("SY0189", "77672528", telephone, content + "【企捷】", "", ""); //群发
                //}
                //else
                //{
                //    string re = api.Send2("SY0189", "77672528", telephone, content + "【企捷】", "", "");
                //}

            }
            catch { }
        }





        private int rep = 0;

        /// <summary>
        /// 生成随机不重复的字符串（分享码用）
        /// </summary>
        /// <param name="codeCount"></param>
        /// <returns></returns>
        public  string GenerateCheckCode(int codeCount)
        {
            string str = string.Empty;
            long num2 = DateTime.Now.Ticks + this.rep;
            this.rep++;
            Random random = new Random(((int)(((ulong)num2) & 0xffffffffL)) | ((int)(num2 >> this.rep)));
            for (int i = 0; i < codeCount; i++)
            {
                char ch;
                int num = random.Next();
                if ((num % 2) == 0)
                {
                    ch = (char)(0x30 + ((ushort)(num % 10)));
                }
                else
                {
                    ch = (char)(0x41 + ((ushort)(num % 0x1a)));
                }
                str = str + ch.ToString();
            }
            return str;
        }
    }
}